/**
 * 邮箱设置
 * */
import React, { useState } from 'react';
import { Modal, Input, Form, Select, message, Row, Col, Spin } from 'antd';
import { fetchCompany } from '@/containers/service';
import { useRequest, defaultFormatResult } from '@/hooks';
import { saveRecruitEmailCompany, checkEmailAccount } from '../../service';
import { CompanySelect } from '..';

const formItemLayout = {
    labelCol: {
        sm: { span: 4 }
    },
    wrapperCol: {
        sm: { span: 18 }
    }
};
const emailSuffixDict = ['@vv.cn', '@vv.com.sg', '@gffamilyoffice.com', '@gfam.com.sg', '@wkcfamilyoffice.com.sg'];
const EmailCompanyConfigs = ({
    form,
    handleOnCancel,
    handleModalSave,
    visible,
    emailInfo = {},
    disabledList = [],
    defaultOrg
}) => {
    const { getFieldDecorator, validateFields, resetFields } = form;
    const [formValue, setFormValue] = useState(null);
    const { data: orgList, loading: orgLoading } = useRequest(
        () =>
            fetchCompany({
                // organizationPermissions: 1,
                showTreeFlag: 0
            }),
        {
            ...defaultFormatResult
        }
    );
    // 保存邮箱
    const { loading: saveLoading, run: handleSaveEmail } = useRequest(() => saveRecruitEmailCompany(formValue), {
        manual: true,
        onSuccess: result => {
            const { code, msg } = result;
            if (code === 10000) {
                if (emailInfo.id) {
                    message.success('成功编辑邮箱');
                } else {
                    message.success('成功新增邮箱');
                }
                handleModalSave(true);
                resetFields();
            } else {
                message.error(msg);
            }
        }
    });

    // 检查邮箱是否正确
    const { loading: checkLoading, run: handleCheckEmail } = useRequest(value => checkEmailAccount(value), {
        manual: true,
        onSuccess: result => {
            const { code, msg } = result;
            if (code === 10000) {
                handleSaveEmail();
            } else {
                message.error(msg);
            }
        }
    });

    // 确定
    const handleOk = () => {
        validateFields((err, values) => {
            if (err) {
                return;
            }
            const next = {
                email: values.emailPrefix + values.emailSuffix,
                pwd: values.password
            };
            setFormValue({
                email: values.emailPrefix + values.emailSuffix,
                password: values.password,
                companyCode: values.companyCode,
                id: emailInfo.id || null
            });
            handleCheckEmail(next);
        });
    };

    // 取消
    const handleCancel = () => {
        resetFields();
        handleOnCancel();
    };

    return (
        <Modal
            title={emailInfo.id ? '编辑邮箱' : '新增邮箱'}
            visible={visible}
            onOk={handleOk}
            onCancel={handleCancel}
            width={640}
            confirmLoading={checkLoading || saveLoading}
        >
            <Form {...formItemLayout} labelAlign="right" style={{ paddingTop: '30px' }}>
                <Spin spinning={orgLoading}>
                    {!defaultOrg ? (
                        <Form.Item label="适用行政机构">
                            {form.getFieldDecorator('companyCode', {
                                initialValue: emailInfo.companyCode || null,
                                rules: [{ required: true, message: '请选择或输入行政机构' }]
                            })(
                                <CompanySelect
                                    treeCheckable={false}
                                    dataSource={orgList || []}
                                    disabledKeys={disabledList}
                                />
                            )}
                        </Form.Item>
                    ) : (
                        <Form.Item label="适用行政机构">
                            <span>全集团</span>
                        </Form.Item>
                    )}
                </Spin>

                <Form.Item label="通知发件邮箱" style={{ marginBottom: 0 }} required>
                    <Row gutter={8}>
                        <Col span={12}>
                            <Form.Item>
                                {getFieldDecorator('emailPrefix', {
                                    initialValue: emailInfo?.email?.split('@')?.[0] || '',
                                    rules: [
                                        {
                                            required: true,
                                            validator(rule, value, callback) {
                                                if (!value) {
                                                    callback('请输入通知发件邮箱');
                                                }
                                                // else if (
                                                //     usedEmail
                                                //         .filter(item => item !== emailInfo?.email || '')
                                                //         .includes(value + getFieldValue('emailSuffix'))
                                                // ) {
                                                //     callback('发送通知邮箱已存在，请重新输入');
                                                // }
                                                callback();
                                            }
                                        }
                                    ]
                                })(<Input placeholder="请输入" maxLength={20} />)}
                            </Form.Item>
                        </Col>
                        <Col span={12}>
                            <Form.Item>
                                {getFieldDecorator('emailSuffix', {
                                    initialValue: `@${emailInfo?.email?.split('@')?.[1] || 'vv.cn'}`
                                    // rules: [
                                    //     {
                                    //         required: true,
                                    //         validator: (rule, value, callback) => {
                                    //             if (value) {
                                    //                 form.validateFields(['emailPrefix']);
                                    //             }
                                    //             callback();
                                    //         }
                                    //     }
                                    // ]
                                })(
                                    <Select style={{ width: '100%' }}>
                                        {emailSuffixDict.map(item => (
                                            <Select.Option value={item} key={item}>
                                                {item}
                                            </Select.Option>
                                        ))}
                                    </Select>
                                )}
                            </Form.Item>
                        </Col>
                    </Row>
                </Form.Item>
                <Form.Item label="密码">
                    {getFieldDecorator('password', {
                        initialValue: emailInfo.password || '',
                        rules: [{ required: true, message: '请输入密码' }]
                    })(
                        <Input.Password
                            placeholder="请输入"
                            type="search"
                            autoComplete="new-password"
                            maxLength={20}
                            visibilityToggle={false}
                        />
                    )}
                </Form.Item>
            </Form>
        </Modal>
    );
};
export default Form.create()(EmailCompanyConfigs);
